Lesson 1 - Intermediate exercise
Translate the following code examples.
# intermediate example 1
def min(x,y):
if x < y: return x
else: return y
print min( min (32, 12), min (43, 13))
- call min with 32 and 12
- if x is less than y then return x otherwise return y
- call min with 43 and 13
- if x is less than y then return x otherwise return y
- print the result of min with the results of line 2 and 4
Toggle answer
# intermediate example 2
def factorial(x):
n = 1
while x > 0:
n = n * x
x = x - 1
return n
print factorial(4)
print factorial(5)
- call factorial(4)
- store 1 to n
- repeat while x is greater than 0
- multiply n by x and store the result
- subtract one to x
- jump back to line 3
- return n
- print the result of factorial(4)
- call factorial(5) by repeating lines 2 to 7
Toggle answer
# intermediate example 3
star = 10
text = ""
x = 1
while x <= star:
text = text + "*"
print text
x = x + 1
- set star to be 10
- make text empty
- set x to be 1
- while x is still less than star
- add a star to text
- print out the stars
- add one to x
- jump to line 4
Toggle answer